package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.web;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.alibaba.algo.cooperation.common.PagerEntity;
import com.alibaba.algo.cooperation.feign.service.EmployeeFeignService;
import com.alibaba.algo.cooperation.feign.vo.req.FeignSelectEmployeeListRequestVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.pagehelper.PageInfo;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.FlowProcessService;
import com.iwhalecloud.citybrain.flow.platform.manager.common.ResponseResult;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.monitor.FlowRecordVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.monitor.FlowTaskTraceVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.task.FlowTaskFinishedNoticeQueryVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.task.FlowUserTaskRoleInfoVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowModelRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowMonitorRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowTaskFinishedNoticeRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowUserTaskRoleInfoRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.entities.FlowActivityApprover;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.entities.FlowTaskFinishedNotice;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.mapper.FlowActivityApproverDAO;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.mapper.FlowTaskFinishedNoticeDAO;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.mapper.FlowTaskInstApproverDAO;
import org.flowable.engine.DynamicBpmnService;
import org.flowable.engine.HistoryService;
import org.flowable.engine.ManagementService;
import org.flowable.engine.common.impl.cfg.IdGenerator;
import org.flowable.engine.common.impl.interceptor.Command;
import org.flowable.engine.common.impl.interceptor.CommandContext;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.TaskHelper;
import org.flowable.task.service.TaskService;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;

/**
 * @author lilh
 * @date 2019-12-11 16:25
 */
@RestController
@RequestMapping
public class HealthCheckController {

    private Logger  logger  = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private HistoryService historyService;

    @Autowired
    private ManagementService  managementService;

    @Autowired
    private EmployeeFeignService  employeeFeignService;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private FlowUserTaskRoleInfoRepository  flowUserTaskRoleInfoRepository;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private   FlowTaskFinishedNoticeRepository  flowTaskFinishedNoticeRepository;

    @GetMapping("/healthCheck")
    public String healthCheck() {
        return "ok";
    }

    @RequestMapping(value = "/test")
    public Object test() {
        JSONArray array = new JSONArray();
        array.add(new HashMap<String, String>(){

            private static final long serialVersionUID = 4786439833840031295L;

            {
                put("code", "yuwen");
                put("desc", "语文");
            }
        });
        array.add(new HashMap<String, String>(){


            private static final long serialVersionUID = 1044118121395073354L;

            {
                put("code", "shuxue");
                put("desc", "数学");
            }
        });

        array.add(new HashMap<String, String>(){
            private static final long serialVersionUID = -6179844998391246741L;

            {
                put("code", "yingyu");
                put("desc", "英语");
            }
        });

        //测试历史变量
        historyService.createHistoricVariableInstanceQuery().taskId("");


        return array;
    }

    @RequestMapping(value = "/test/getHisVariable")
    public   String  testHistoricalVariable(@RequestParam("taskId") String taskId){
        List<HistoricVariableInstance> variables = historyService.createHistoricVariableInstanceQuery().taskId(taskId).list();
        logger.info("Variables:"+ JSON.toJSONString(variables, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
        return  "OK";
    }

    @RequestMapping(value = "/test/dynamicBpmnService")
    public   String  dynamicBpmnService(@RequestParam("processDefinitionId") String processDefinitionId){

        DynamicBpmnService dynamicBpmnService = managementService.executeCommand(
                new Command<DynamicBpmnService>() {
                    public   DynamicBpmnService execute(CommandContext commandContext){
                        return CommandContextUtil.getProcessEngineConfiguration().getDynamicBpmnService();
                    }
                }
        );
        //ObjectNode objectNode = dynamicBpmnService.getProcessDefinitionInfo(processDefinitionId);
        //logger.info("ObjectNode:"+JSON.toJSONString(objectNode, SerializerFeature.PrettyFormat));
        ObjectNode  users = dynamicBpmnService.changeUserTaskCandidateUsers("code001", Arrays.asList("aaa", "bbb"));
        dynamicBpmnService.saveProcessDefinitionInfo(processDefinitionId, users);
        return  "OK";
    }

    //测试EmployeeFeignService.selectPage接口
    @RequestMapping(value = "/test/employee/selectPage")
    public   String  selectEmployeePage(@RequestParam("employeeName") String employeeName){
        FeignSelectEmployeeListRequestVO  requestVO = new  FeignSelectEmployeeListRequestVO();
        requestVO.setEmployeeName(employeeName);
        requestVO.setPageIndex(1);
        requestVO.setPageSize(10);
        PagerEntity  pagerEntity =  employeeFeignService.selectPage(requestVO);
        logger.info("PagerEntity:"+pagerEntity);
        logger.info(JSON.toJSONString(pagerEntity, SerializerFeature.PrettyFormat));
        return  "OK";
    }

    @RequestMapping(value = "/test/changeAssign")
    public   String  changeAssign(@RequestParam("taskId") String taskId, @RequestParam("assignee") String assignee ){
        managementService.executeCommand(new Command<Void>() {
            @Override
            public Void  execute(CommandContext commandContext) {
                TaskService taskService = CommandContextUtil.getTaskService();
                TaskEntity task = taskService.getTask(taskId);
                //taskService.changeTaskAssignee(task, assignee);
                TaskHelper.changeTaskAssignee(task, assignee);
                return null;
            }
        });
        return  "OK";
    }

    @RequestMapping(value = "/test/addUserTaskRoleInfo")
    public   String  testFlowUserTaskRoleInfo(){
        FlowUserTaskRoleInfoVo  vo = new  FlowUserTaskRoleInfoVo();
        String id = idGenerator.getNextId();
        String candidateUsers = "11";
        String roleIds = "22";
        vo.setId(id);
        vo.setDeployId("deploy111");
        vo.setCandidateUsers(candidateUsers);
        vo.setRoleIds(roleIds);
        vo.setCreateTime(new Date());
        vo.setUpdateTime(vo.getCreateTime());
        int count = flowUserTaskRoleInfoRepository.insertUserTaskRoleInfo(vo);
        logger.info("count:"+count);
        return  "OK";
    }

    @Autowired
    private FlowModelRepository flowModelRepository;

    //@PostConstruct
    public  void  init(){
       /* ModelQueryVo modelQueryVo = new  ModelQueryVo();
        modelQueryVo.setCategory("DESIGN");
        modelQueryVo.setPageSize(1000);
        modelQueryVo.setSearchKey("202106181823");
        ResponseResult result = flowModelRepository.list(modelQueryVo);
        List<FlowModelQueryInfo> infoList = (List<FlowModelQueryInfo>)result.getDatas();
        logger.info("InfoList Size:"+infoList.size());*/
        logger.info("Test...");
    }

    @Autowired
    private FlowActivityApproverDAO  flowActivityApproverDAO;

    //@PostConstruct
    public  void   flowActivityApproverDAOTest(){
        logger.info("flowActivityApproverDAO:"+flowActivityApproverDAO);

        /*FlowActivityApprover  flowActivityApprover = new  FlowActivityApprover();
        flowActivityApprover.setDeployId("aaaa");
        flowActivityApprover.setActivityId("xxx");
        flowActivityApprover.setCode("xxx");
        flowActivityApprover.setName("xxxx");
        flowActivityApprover.setType("STA");
        flowActivityApprover.setCreateTime(new Date());
        flowActivityApproverDAO.insertSelective(flowActivityApprover);*/

        List<FlowActivityApprover>  approverList = flowActivityApproverDAO.selectByDeployIdAndActivityId("aaaa", "xxx");
        logger.info("approverList:"+approverList);
    }

    @Autowired
    private FlowTaskInstApproverDAO flowTaskInstApproverDAO;

    //@PostConstruct
    public  void   flowTaskInstApproverDAOTest(){
       /* FlowTaskInstApprover flowTaskInstApprover = new FlowTaskInstApprover();
        flowTaskInstApprover.setTaskId("t1");
        flowTaskInstApprover.setUserId("11111");
        flowTaskInstApprover.setUserName("用户1");
        flowTaskInstApprover.setCreateTime(new Date());
        flowTaskInstApproverDAO.insertSelective(flowTaskInstApprover);*/

       //List<FlowTaskInstApprover>  approverList =  flowTaskInstApproverDAO.selectListByTaskId("t1");
       //logger.info("List:"+approverList);
    }

    @Autowired
    private FlowMonitorRepository flowMonitorRepository;

    @Autowired
    private FlowProcessService flowProcessService;

    //@PostConstruct
    public  void  flowRecordList(){
        String procInstId = "7aee47890bcd11ec9a401ebfc022a949";
        List<FlowRecordVo> recordVoList = flowMonitorRepository.listFlowRecords(procInstId);
        logger.info("FlowRecordVoList:"+recordVoList);
    }

    //@PostConstruct
    public  void  flowProcessServiceTest(){
        String procInstId = "7aee47890bcd11ec9a401ebfc022a949";
        ResponseResult result = flowProcessService.getProcessInstanceDiagramAndInfo(procInstId);
        logger.info("Result:"+result);
    }

    @PostConstruct
    public  void  printJdbcTemplate(){
        logger.info("JdbcTemplate:"+jdbcTemplate);
    }

    @Autowired
    private FlowTaskFinishedNoticeDAO  flowTaskFinishedNoticeDAO;

    //@PostConstruct
    public  void   flowTaskFinishedNoticeDAO(){
        FlowTaskFinishedNotice  flowTaskFinishedNotice = new FlowTaskFinishedNotice();
        flowTaskFinishedNotice.setTaskId("dafdsafsafwfdsfas");
        flowTaskFinishedNotice.setUserId(1L);
        flowTaskFinishedNotice.setUserName("ggg");
        flowTaskFinishedNotice.setEmployeeCode("eee1");
        flowTaskFinishedNotice.setCreateTime(new Date());
        flowTaskFinishedNoticeDAO.insertSelective(flowTaskFinishedNotice);
    }

    //@RequestMapping(value = "/test/selectPageListTest")
    public  void    selectPageListTest(){
        FlowTaskFinishedNoticeQueryVo  flowTaskFinishedNoticeQueryVo = new FlowTaskFinishedNoticeQueryVo();
        //flowTaskFinishedNoticeQueryVo.setEmployeeCode("10008");
        flowTaskFinishedNoticeQueryVo.setPageNum(1);
        flowTaskFinishedNoticeQueryVo.setPageSize(2);
        PageInfo<FlowTaskTraceVo>  pageInfo = flowTaskFinishedNoticeRepository.selectPageList(flowTaskFinishedNoticeQueryVo);
        logger.info("PageInfo:"+pageInfo);
    }

    @Autowired
    private   FlowPlatformClientController flowPlatformClientController;

    //@PostConstruct
    public  void  GetTaskInst(){
        ResponseResult result =  flowPlatformClientController.getTaskInst("1dd03053109411ecb31300163e14e5a7", "ggg");
        logger.info("Result:"+result);
    }

    //@PostConstruct
    public  void   testJdbcTemplate(){
        logger.info("JdbcTemplate:"+jdbcTemplate);
    }
}
